"ui";
ui.layout(
    <vertical w='*' h='*' padding='10 0'>
        <input id='sendText' textSize='15' lines='10' hint='输入要发送的文字'></input>
        <button id='saveText'>确认</button>
        <text id='groupNumber' textColor='black' marginTop='10'></text>
        <button marginTop='20' id='getGroup'>获取群组</button>
        <frame w='*' h='*'>
            <button id='start' marginBottom='50' padding='15' bg="#00ff00" layout_gravity="bottom" w='*' h='auto'>开启发送消息</button>
        </frame>

    </vertical>
);
auto.waitFor()
setScreenMetrics(device.width, device.height);
// 创建本地存储
let storage = storages.create('weixinGroupStorage')
// 添加要发送的文本
let text_local = storage.get('sendText')
text_local = text_local ? text_local : ''
ui.sendText.text(text_local)

getGroupNumber()
ui.getGroup.click(() => {
    this.openApp(type = 'open')
})
ui.start.click(() => {
    this.openApp(type = 'send')
})

ui.saveText.click(() => {
    let text = ui.sendText.getText()
    storage.put('sendText', '' + text)
    toast('文本保存成功')
})

// 获取, 并显示群组数量
function getGroupNumber() {
    let number = getStorage().length || 0
    ui.groupNumber.text(`获取到的群组：${number}`)
}

function openApp(type) {
    let Threads = threads.start(function () {
        launchApp('微信')
        sleep(2000)
        let tongxunlu = id("icon_tv").text("通讯录").findOne().bounds()
        // 点击通讯录
        click(tongxunlu.centerX(), tongxunlu.centerY())
        sleep(2000)
        let qunliao = id("n9").className("android.widget.TextView").text("群聊").findOne().bounds()
        // 点击群聊
        click(qunliao.centerX(), qunliao.centerY())
        sleep(2000)
        if (type === 'open') {

            // 获取群组列表
            let allItems = []
            while (true) {
                let grouptList = id("cg1").className("android.widget.TextView").find()
                grouptList.forEach(item => {
                    if (!allItems.includes(item.text())) {
                        allItems.push(item.text());
                    }
                });
                if (className("android.widget.FrameLayout").depth(12).exists()) {
                    break;
                }
                let width = device.width;
                let height = device.height;
                sleep("1000");
                swipe(width / 2, height / 3 * 2, width / 2, height / 3 * 1, 1500);
            }
            setStorage(allItems)
            let data = getStorage()
            ui.post(() => {
                ui.groupNumber.text(`获取到的群组：${data.length}`);
            });
            sleep(500)
            back()
            sleep(500)
            back()
            toast('获取群组完成')
            Threads.interrupt()
        } else if (type === 'send') {
            let data = getStorage()
            data.forEach(item => {
                // 发送消息给群组
                let search = id("jgr").findOne().bounds()
                click(search.centerX(), search.centerY())
                sleep(2000)
                let searchInput = className("android.widget.EditText").findOne().setText(item)
                sleep(3000)

                let searchItem = id('cg1').text(item).findOnce()
                if (!searchItem) {
                    click(276, 358)
                    console.log(111);
                } else {
                    let groupItem = id("cg1").text(item).findOne().bounds()
                    click(groupItem.centerX(), groupItem.centerY())
                    console.log(222);
                }
                sleep(2000)
                let text = storage.get('sendText')
                id("bkk").className("android.widget.EditText").findOne().setText(text)
                let send = id("bql").findOne().bounds()
                click(send.centerX(), send.centerY())
                sleep(2000)
                let back = id("a4p").findOne().bounds()
                click(back.centerX(), back.centerY())
                console.log(`完成 ${item} 的消息发送`);
                sleep(2000)
            })
            toast('当前任务完成')
        }
    })
}

// 存储群组storage
function setStorage(numberList) {
    if (!numberList) numberList = []
    numberList = JSON.stringify(numberList)
    storage.put('groupNumberList', numberList)
}
// 获取群组storage
function getStorage() {
    return storage.get('groupNumberList') ? JSON.parse(storage.get('groupNumberList')) : []
}
